const {handleAdd, handleDel, handleModify, handleList, handleMove} = require('../models/menu')

// 新增
const add = async (ctx, next) => {
    // session 验证
    if (JSON.stringify(ctx.session) === '{}') {
        return ctx.body = {code: 401, data: null, msg: '登录过期'};
    }
    if (ctx.session.role === 'root') {
        ctx.body = await handleAdd(ctx.request.body).catch(err => ctx.body = err);
    } else if (ctx.session.role === 'user') {
        ctx.body = await handleAdd({userId: ctx.session.id, ...ctx.request.body}).catch(err => ctx.body = err);
    } else {
        ctx.body = {code: 401, data: null, msg: '暂无权限'}
    }

}

// 修改
const modify = async (ctx, next) => {
    // session 验证
    if (JSON.stringify(ctx.session) === '{}') {
        return ctx.body = {code: 401, data: null, msg: '登录过期'};
    }
    if (ctx.session.role === 'root') {
        ctx.body = await handleModify({...ctx.request.body, ...ctx.params}).catch(err => ctx.body = err);
    } else if (ctx.session.role === 'user') {
        ctx.body = await handleModify({userId: ctx.session.id, ...ctx.request.body, ...ctx.params}).catch(err => ctx.body = err);
    } else {
        ctx.body = {code: 401, data: null, msg: '暂无权限'}
    }
}

// 查询
const list = async (ctx, next) => {
    ctx.body = await handleList(ctx.request.query).catch(err => ctx.body = err);
}

// 删除
const del = async (ctx, next) => {
    // session 验证
    if (JSON.stringify(ctx.session) === '{}') {
        return ctx.body = {code: 401, data: null, msg: '登录过期'};
    }
    if (ctx.session.role === 'root') {
        ctx.body = await handleDel({...ctx.request.body, ...ctx.params}).catch(err => ctx.body = err);
    } else if (ctx.session.role === 'user') {
        ctx.body = await handleDel({userId: ctx.session.id, ...ctx.params}).catch(err => ctx.body = err);
    } else {
        ctx.body = {code: 401, data: null, msg: '暂无权限'}
    }
}


// 排序更改
const move = async (ctx, next) => {
    // session 验证
    if (JSON.stringify(ctx.session) === '{}') {
        return ctx.body = {code: 401, data: null, msg: '登录过期'};
    }
    if (ctx.session.role === 'root') {
        ctx.body = await handleMove({...ctx.request.body, ...ctx.params}).catch(err => ctx.body = err);
    } else if (ctx.session.role === 'user') {
        ctx.body = await handleMove({userId: ctx.session.id, ...ctx.request.body, ...ctx.params}).catch(err => ctx.body = err);
    } else {
        ctx.body = {code: 401, data: null, msg: '暂无权限'}
    }
}

module.exports = {add, del, modify, list, move}
